package com.dongwu.job;

import java.io.File;
import java.io.FilenameFilter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.dongwu.manager.dto.ProductData;
import com.dongwu.manager.service.ProductService;
import com.google.common.collect.Lists;




@Component
@EnableScheduling  
public class YKproductImportJob {
	@Value("${dongwu.ykproduct.filepath}")
	private String filepath;
	@Value("${dongwu.ykproduct.targetpath}")
	private String targetPath;
	
	@Resource
	private ProductService productService;
	
	public File[] readFileByFilenameHash(String filePath) {
		final File iFilePath = new File(filePath);
		final File[] contents = iFilePath.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				String filePath = dir.getAbsolutePath() + File.separator + name;
				File file = new File(filePath);
				if (file.isDirectory()) {
					return false;
				}
				int hash = name.hashCode();
				if (hash < 0) {
					hash = -hash;	
				}
				return true;
			}

		});
		return contents;
	}
	
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
    @Scheduled(fixedDelay = 5000)
    public void process() {
    	List<ProductData> datas=this.fetchData();
    	if(null!=datas&&!datas.isEmpty()){
    		productService.syncProduct(datas);
    	}
    	
    }
	
	
	
	public List<ProductData> fetchData() {
		

		final File[] contents = this.readFileByFilenameHash(filepath);

		List<ProductData> storeMerchantnoList = Lists
				.newArrayList();
		if (contents == null||contents.length==0) {
			return storeMerchantnoList;
		}

		for (File file : contents) {
			String fileName = file.getName();
//			String handler = fileName.substring(fileName.indexOf(".") + 1,
//					fileName.lastIndexOf("."));
			logger.info("start handle file:{}", file.getAbsolutePath());

			if (!file.exists()) {
				logger.warn("file don't exsit, continue loop");
				continue;
			}

			try {
				List<ProductData> productDatas = Lists
						.newArrayList();
				if (fileName.endsWith(".xls")) {
					//2003表格
					try (HSSFWorkbook book = new HSSFWorkbook(new POIFSFileSystem(file))) {
						HSSFSheet sheet = book.getSheetAt(0);
						for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
							ProductData productData=this.getProductData(sheet.getRow(i));
							productDatas.add(productData);
						}
					}
				}else if (fileName.endsWith(".xlsx")) {
					//2007表格
					try (XSSFWorkbook book = new XSSFWorkbook(file)) {
						XSSFSheet sheet = book.getSheetAt(0);
						for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
							ProductData productData=this.getProductData(sheet.getRow(i));
							productDatas.add(productData);
						}
					}
				}
				storeMerchantnoList.addAll(productDatas);
			} catch (final Exception ex) {
				logger.error(ex.getMessage(), ex);
				moveFile2TargetPath(file,filepath);
			}
			moveFile2TargetPath(file,filepath);
		}

		return storeMerchantnoList;
	}
	
	private ProductData getProductData(Row row)
	{
		String name = getValue(row.getCell(0),"0");
		String price = getValue(row.getCell(1),"0");
		String integral =getValue(row.getCell(2),"0");
		String slideImage = getValue(row.getCell(3),"0");
		String introduction = getValue(row.getCell(4),"0");
		String outSn = getValue(row.getCell(5),"0");
		String bussinesSn = getValue(row.getCell(6),"0");
		String image = getValue(row.getCell(7),"0");
		String pathurl = getValue(row.getCell(8),"0");
		String goodsid = getValue(row.getCell(9),"0");
		ProductData data = new ProductData();
		data.setName(name);
		data.setPrice(new BigDecimal(price));
		data.setRewardPoint(Long.valueOf(integral));
		data.setSlideImage(slideImage);
		data.setIntroduction(introduction);
		data.setOutSn(outSn);
		data.setBussinesSn(bussinesSn);
		data.setImage(image);
		data.setPathmobile(pathurl);
		data.setGoodsid(goodsid);
		return data;
	}

	@SuppressWarnings("deprecation")
	private String getValue(Cell hssfCell,String format) {
		if (hssfCell==null) {
			return "";
		}
		switch (hssfCell.getCellType()) {
			case Cell.CELL_TYPE_BOOLEAN:
				return hssfCell.getBooleanCellValue()?"TRUE":"FALSE";
			case Cell.CELL_TYPE_ERROR:
				return ErrorEval.getText(hssfCell.getErrorCellValue());
			case Cell.CELL_TYPE_FORMULA:
				return hssfCell.getCellFormula();
			case Cell.CELL_TYPE_NUMERIC:
				if (DateUtil.isCellDateFormatted(hssfCell)) {
					DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
					return df.format(hssfCell.getDateCellValue());
				}
				DecimalFormat df = new DecimalFormat(format);
				return df.format(hssfCell.getNumericCellValue());
			case Cell.CELL_TYPE_STRING:
				return hssfCell.getStringCellValue();
			default:
				return "";
		}
	}

	private void moveFile2TargetPath(File file,String targetPath) {
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String curTime = dateFormatter.format(new Date());
		file.renameTo(new File(String.format("%s%s%s",targetPath,curTime,
				file.getName())));
	}
}